<template>
  <pro-layout
    :menus="menus"
    :collapsed="collapsed"
    :mediaQuery="query"
    :isMobile="isMobile"
    :handleMediaQuery="handleMediaQuery"
    :handleCollapse="handleCollapse"
    :i18nRender="i18nRender"
    v-bind="settings"
    :siderWidth="currentMenu.children.filter((element) => !element.hidden).length ? 256 : 100"
  >
    <!-- 1.0.0+ 版本 pro-layout 提供 API，
          我们推荐使用这种方式进行 LOGO 和 title 自定义
    -->
    <template v-slot:menuRender v-if="!collapsed">
      <a-row>
        <a-col :span="currentMenu.children.filter((element) => !element.hidden).length ? 10 : 24" class="sMainMenus">
          <div
            :class="item.name == currentMenu.name ? { activeMenu: true } : {}"
            class="sMainMenusTitle"
            v-for="(item, index) in menus"
            :key="index"
            @click="chengeCurrentMenu(item)"
          >
            <a-icon :type="item.meta.icon" style="margin-right: 7px"></a-icon>{{ item.meta.title }}
          </div>
        </a-col>
        <a-col :span="currentMenu.children.filter((element) => !element.hidden).length ? 14 : 0" class="sSubMenus">
          <div
            :class="el.name == currentRoute.name ? { activeRoute: true } : {}"
            class="sSubMenusItem"
            @click="changeCurrentRoute(el)"
            v-for="(el, ind) in currentMenu.children"
            :key="ind"
            v-if="!el.hidden"
          >
            {{ el.meta.title }}
          </div>
        </a-col>
      </a-row>
    </template>
    <template v-slot:menuHeaderRender>
      <div
        :style="
          currentMenu.children.filter((element) => !element.hidden).length
            ? {}
            : collapsed
            ? {}
            : { paddingLeft: '10px' }
        "
      >
        <img style="position: relative; top: -2px" :src="admin_logo" />
        <h1 style="color: rgba(0, 21, 41, 0.8)">{{ title }}</h1>
      </div>
    </template>
    <a-modal
      v-model="wantPay"
      :title="weChatPayName"
      @ok="showWechatPay"
      :width="430"
      @cancel="showWechatPay"
      :maskClosable="false"
      :closable="false"
      :keyboard="false"
      :footer="null"
    >
      <a-alert :message="order_desc" banner />
      <a-alert type="error" message="二维码已过期" banner v-if="is_expire" />
      <div class="wechatQrcodeBox">
        <div></div>
        <img :src="weChatQrcode" class="weChatQrcode" style="width: 20rem; height: 20rem" />
        <div></div>
      </div>
    </a-modal>
    <!-- <setting-drawer :settings="settings" @change="handleSettingChange" /> -->
    <template v-slot:rightContentRender>
      <a class="diyLogo" href="#/">
        <img
          style="
            position: relative;
            top: -5px;
            height: 32px;
            width: auto;
            vertical-align: middle;
            display: inline-block;
          "
          :src="admin_logo"
        />
        <!-- <h1 style="color: rgba(0, 21, 41, 0.8);font-size: 20px;display:inline-block;margin: 0 0 0 12px;font-family: Avenir, Helvetica Neue, Arial, Helvetica, sans-serif;font-weight: 600;">{{ title }}</h1> -->
      </a>
      <a-icon
        :type="collapsed ? 'menu-unfold' : 'menu-fold'"
        @click="handleCollapse(!collapsed)"
        :style="{ fontSize: '20px' }"
      />
      <a-button
        type="primary"
        @click="onBack"
        v-if="(isShowBack || isSaasSupplier) && !isMdBack"
        style="margin-left: 20px; position: relative; top: -2px"
      >
        返回平台
      </a-button>
      <a-button
        type="primary"
        @click="onBackMd"
        v-if="isMdBack"
        style="margin-left: 20px; position: relative; top: -2px"
      >
        返回商城
      </a-button>
      <span style="margin-left: 20px; font-size: 18px; font-weight: bold" v-if="!isPlatform && isShowBack && !isMd"
        ><a-divider type="vertical" />商城后台</span
      >
      <span style="margin-left: 20px; font-size: 18px; font-weight: bold" v-else-if="isMd"
        ><a-divider type="vertical" />门店后台</span
      >
      <span style="margin-left: 20px; font-size: 18px; font-weight: bold" v-else-if="isPlatform && !isSupplier && !daili"
        ><a-divider type="vertical" />平台后台</span
      >
      <span style="margin-left: 20px; font-size: 18px; font-weight: bold" v-else-if="isPlatform && isSupplier"
        ><a-divider type="vertical" />供货商后台</span
      >
      <span style="margin-left: 20px; font-size: 18px; font-weight: bold" v-else-if="daili"
        ><a-divider type="vertical" />{{ userInfo.info.typename }}</span
      >

      <right-content :top-menu="settings.layout === 'topmenu'" :is-mobile="isMobile" :theme="settings.theme" />
      <div class="clear-storage-btn">
        <a-button type="danger" @click="showClearCache = true">清除缓存</a-button>
      </div>
    </template>
    <!-- 加入multiTab支持 -->
    <!-- <multi-tab v-if="multiTab"></multi-tab> -->
    <a-modal v-model="showClearCache" :afterClose="function (){cacheList = ['data']}" title="清除缓存" @ok="clearCache">
      <a-checkbox-group v-model="cacheList">
        <a-checkbox value="data"> 缓存数据 </a-checkbox>
        <a-checkbox value="pic"> 缓存图片 </a-checkbox>
        <a-checkbox value="update"> 更新缓存 </a-checkbox>
      </a-checkbox-group>
    </a-modal>
    <router-view />
  </pro-layout>
</template>

<script>
import storage from 'store'
import store from '@/store/'
import { SettingDrawer, updateTheme } from '@ant-design-vue/pro-layout'
import { i18nRender } from '@/locales'
import { mapState } from 'vuex'
import { CONTENT_WIDTH_TYPE, SIDEBAR_TYPE, TOGGLE_MOBILE_TYPE, ACCESS_TOKEN } from '@/store/mutation-types'
import { generateTokenBySaas } from '@/api/auth'

import defaultSettings from '@/config/defaultSettings'
import RightContent from '@/components/GlobalHeader/RightContent'
import MultiTab from '@/components/MultiTab'
import logoImg from '@/assets/logo.png'
import { getStoreCost, payFee, isPay } from '@/api/store'
import { submit } from '@/api/setting/cache'

export default {
  name: 'BasicLayout',
  components: {
    SettingDrawer,
    RightContent,
    MultiTab,
  },
  data() {
    return {
      showClearCache: false,
      cacheList:['data'],
      currentMenu: {},
      currentRoute: {},
      // preview.pro.antdv.com only use.
      isProPreviewSite: process.env.VUE_APP_PREVIEW === 'true' && process.env.NODE_ENV !== 'development',
      // end

      // base
      menus: [],
      // 侧栏收起状态
      collapsed: false,
      title: store.getters.admin_name || defaultSettings.title,
      settings: {
        // 布局类型
        layout: defaultSettings.layout, // 'sidemenu', 'topmenu'
        // CONTENT_WIDTH_TYPE
        contentWidth: defaultSettings.layout === 'sidemenu' ? CONTENT_WIDTH_TYPE.Fluid : defaultSettings.contentWidth,
        // 主题 'dark' | 'light'
        theme: defaultSettings.navTheme,
        // 主色调
        primaryColor: defaultSettings.primaryColor,
        fixedHeader: defaultSettings.fixedHeader,
        fixSiderbar: defaultSettings.fixSiderbar,
        colorWeak: defaultSettings.colorWeak,
        hideHintAlert: false,
        hideCopyButton: false,
      },
      // 媒体查询
      query: {},
      // 是否手机模式
      isMobile: false,
      wantPay: false,
      weChatQrcode: '',
      weChatPayName: '',
      is_expire: false,
      is_pay: '',
      order_desc: '',
      total_price: '',
      end_time: '',
    }
  },
  watch: {
    currentRouteObj: {
      handler(val) {
        const routes = this.mainMenu.find((item) => item.path === '/')
        const menus = (routes && routes.children) || []
        menus.forEach((element) => {
          if (element.children) {
            element.children.forEach((item) => {
              if (item.name == val.name) {
                this.currentMenu = element
                this.currentRoute = item
                return false
              }
              if (item.children) {
                item.children.forEach((el) => {
                  if (el.name == val.name) {
                    this.currentMenu = element
                    this.currentRoute = item
                  }
                })
              }
            })
          }
        })
      },
      immediate: true,
    },
  },
  computed: {
    isShowBack() {
      return storage.get('isSaasStore') || storage.get('daili')
    },
    isSaasSupplier() {
      return storage.get('isSaasSupplier')
    },
    isMdBack() {
      return storage.get('isSaasMd')
    },
    isMd() {
      return storage.get('mdId')
    },
    isPlatform() {
      return storage.get('isPlatform')
    },
    isSupplier() {
      return storage.get('isSupplier')
    },
    currentRouteObj() {
      return this.$route
    },
    admin_logo() {
      return this.$store.getters.admin_logo || logoImg
    },
    ...mapState({
      // 动态主路由
      mainMenu: (state) => state.permission.addRouters,
      multiTab: (state) => state.app.multiTab,
      admin_logo:(state) => state.setting.admin_logo,
    }),
    daili() {
      return storage.get('daili')
    },
    userInfo() {
      return this.$store.state.user
    }
  },
  created() {
    console.log(1234,this.mainMenu);

    const routes = this.mainMenu.find((item) => item.path === '/')
    this.menus = (routes && routes.children) || []
    // 处理侧栏收起状态
    this.$watch('collapsed', () => {
      this.$store.commit(SIDEBAR_TYPE, this.collapsed)
    })
    this.$watch('isMobile', () => {
      this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile)
    })
    this.IsStoreWechat()
  },
  mounted() {
    const userAgent = navigator.userAgent
    if (userAgent.indexOf('Edge') > -1) {
      this.$nextTick(() => {
        this.collapsed = !this.collapsed
        setTimeout(() => {
          this.collapsed = !this.collapsed
        }, 16)
      })
    }

    // first update color
    // TIPS: THEME COLOR HANDLER!! PLEASE CHECK THAT!!
    if (process.env.NODE_ENV !== 'production' || process.env.VUE_APP_PREVIEW === 'true') {
      updateTheme(this.settings.primaryColor)
    }
  },
  methods: {
    IsStoreWechat() {
      // console.log(storage.get('isSaasStore'),'isSaasStore'); storage.get('isSaasStore')
      if (true) {
        var storeId = storage.get('storeId')
        var isPlatform = storage.get('isPlatform');
        if (!isPlatform) {
          getStoreCost({ storeId: storeId }).then((res) => {
            if (!res.data.open_price) {
              this.$alert('没有设置商城金额以及有效期', '错误信息', {
                showClose: false,
                showConfirmButton: false,
                showCancelButton: false,
              })
            } else if (res.code === 0 && res.data.is_end === false) {
              payFee({ storeId: storeId }).then((res) => {
                if (res.code === 0 && res.url) {
                  this.wantPay = true
                  this.weChatPayName = res.name
                  this.weChatQrcode = res.url
                  this.order_desc = res.desc
                } else if (res.code !== 0) {
                  this.$message.error(res.msg)
                }
              })
            } else if (res.code === 1) {
            }
          })
        }

      }
    },
    showWechatPay: function () {
      this.is_expire = false
      this.wantPay = false
      clearInterval(this.is_pay)
    },
    i18nRender,
    changeCurrentRoute(el) {
      if (el.meta.target === '_blank') {
        window.open(el.path)
        return
      }
      if (el.redirect && el.children) {
        if (el.redirect != el.children[0].path) {
          el.redirect = el.children[0].path
        }
        this.$router.push({ path: el.redirect })
      } else {
        this.$router.push({ name: el.name })
      }
    },
    chengeCurrentMenu(item) {
      this.IsStoreWechat()
      if (item.path.indexOf('http', 0) > -1) {
        let url = item.path
        const store_id = storage.get('storeId') || 1
        if (url.indexOf('?', 0) > -1) {
          url += '&store_id=' + store_id
        } else {
          url += '?store_id=' + store_id
        }
        if (item.meta.target === '_blank') {
          window.open(url)
        } else {
          window.location.href = url
        }
        return
      }
      console.log(item, 'item.redirect')
      if (item.redirect) {
        if (item.redirect != item.children[0].path) {
          item.redirect = item.children[0].path
        }
        this.$router.push({ path: item.redirect })
      }
      this.currentMenu = item
    },
    handleMediaQuery(val) {
      this.query = val
      if (this.isMobile && !val['screen-xs']) {
        this.isMobile = false
        return
      }
      if (!this.isMobile && val['screen-xs']) {
        this.isMobile = true
        this.collapsed = false
        this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
        // this.settings.fixSiderbar = false
      }
    },
    handleCollapse(val) {
      this.collapsed = val
    },
    handleSettingChange({ type, value }) {
      console.log('type', type, value)
      type && (this.settings[type] = value)
      switch (type) {
        case 'contentWidth':
          this.settings[type] = value
          break
        case 'layout':
          if (value === 'sidemenu') {
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fluid
          } else {
            this.settings.fixSiderbar = false
            this.settings.contentWidth = CONTENT_WIDTH_TYPE.Fixed
          }
          break
      }
    },
    onBack: function () {
      storage.remove('isSaasStore')
      // storage.remove('daili')
      storage.set('isPlatform', true)
      if (storage.get('isSupplier')) {
        const username = storage.get('currentStoreUsername')
        const storeId = 1
        if (!username || !storeId) {
          this.$message.error('返回失败，请退出重新登录')
          return
        }
        generateTokenBySaas({ storeId: storeId, username: username })
          .then((res) => {
            if (res.code == 0) {
              storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
              this.$store.commit('SET_TOKEN', res.data.access_token)
              storage.remove('isSaasSupplier')
              storage.remove('isSupplier')
              window.location.href = '/'
            } else {
              this.$message.error('获取token失败')
            }
          })
          .catch((error) => {
            console.log(error)
          })
          .then(() => {})
      } else {
        if(storage.get('daili')){
          let username = 'admin'
          if(storage.get('goodsAgent')){
            username = storage.get('goodsAgent')

            if (username === 'admin') {
              storage.remove('daili')
            }
          }
          generateTokenBySaas({ username })
          .then((res) => {
            if (res.code == 0) {
              if(!storage.get('goodsAgent')){
                storage.remove('daili')
              }else{
                storage.remove('goodsAgent')
              }
              storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
              this.$store.commit('SET_TOKEN', res.data.access_token)
              storage.remove('isSaasSupplier')
              storage.remove('isSupplier')
              window.location.href = '/'
            } else {
              this.$message.error('获取token失败')
            }
          })
          .catch((error) => {
            console.log(error)
          })
          .then(() => {})
          return;
        }

        window.location.href = '/'
      }

    },
    onBackMd: function () {
      const username = storage.get('currentStoreUsername')
      const storeId = storage.get('storeId')
      if (!username || !storeId) {
        this.$message.error('返回失败，请退出重新登录')
        return
      }
      generateTokenBySaas({ storeId: storeId, username: username })
        .then((res) => {
          if (res.code == 0) {
            storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit('SET_TOKEN', res.data.access_token)
            storage.remove('mdId')
            storage.remove('isSaasMd')
            storage.remove('currentStoreUsername')
            window.location.href = '/'
          } else {
            this.$message.error('获取token失败')
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {})
    },
    clearStorage() {
      submit({}).then((res) => {
        if (res.code == 0) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 点击清除缓存
    clearCache() {
      submit({cache:this.cacheList}).then((res) => {
        if (res.code == 0) {
          this.$message.success(res.msg)
          this.showClearCache = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
  },
}
</script>

<style lang="less">
.ant-pro-global-header {
  height: 48px;
  line-height: 48px;
}
.ant-layout-header {
  height: 48px;
  line-height: 48px;
}
.ant-pro-sider-menu-logo {
  height: 48px;
  line-height: 48px;
}
.ant-menu-inline-collapsed {
  width: auto;
}
.diyLogo {
  padding: 0 22px;
  height: 48px;
  line-height: 48px;
  display: inline-block;
  // vertical-align: top;
}
.ant-pro-sider-menu-logo {
  background: #fff;
}
.ant-pro-global-header-trigger {
  display: none;
}
.sMainMenus {
  padding-top: 12px;
  position: absolute;
  left: 0;
  top: 0px;
  height: calc(100vh - 48px) !important;
  box-sizing: border-box;
  overflow-y: auto;

  .sMainMenusTitle {
    cursor: pointer;
    height: 48px;
    line-height: 48px;
    padding-left: 24px;
    color: rgba(255, 255, 255, 0.65);
    transition: all 0.2s;
    &:hover {
      color: #fff;
    }
  }
}
.sSubMenus {
  position: absolute;
  right: 0;
  top: 0px;
  padding: 12px 15px;
  height: calc(100vh - 48px);
  box-sizing: border-box;
  background: #fff;
  overflow-y: auto;

  /*滚动条区域*/
  &::-webkit-scrollbar{
    width:5px;
    background-color:#fff;
  }

  /*滚动条*/
  &::-webkit-scrollbar-thumb{
    background-color:#1890ff;
  }

  /*滚动条外层轨道*/
  &::-webkit-scrollbar-track {
    background-color:#fff;
    border-radius: 10px;
  }

  .sSubMenusItem {
    height: 40px;
    cursor: pointer;
    line-height: 40px;
    margin: 4px 0;
    padding-left: 15px;
    transition: all 0.2s;
    border-radius: 3px;
    &:hover {
      background: #f9f9f9;
    }
  }
}
.activeMenu {
  background: #fff;
  color: rgb(37, 147, 252) !important;
}
.activeRoute {
  background: rgb(240, 242, 245);
  color: rgb(37, 147, 252) !important;
}
.wechatQrcodeBox {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  margin-top: 10px;
}
.wechatQrcodeBox > div {
  font-size: 16px;
  font-weight: 600;
  margin-left: 20px;
}
.clear-storage-btn {
  float: right;
  margin-right: 16px;
}
@import './BasicLayout.less';
</style>
